<template>
  <view class="trip-container">
    <!-- 行程列表 -->
    <scroll-view 
      class="trip-list" 
      scroll-y 
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="orders.length > 0 ">
        <view 
          class="trip-item" 
          v-for="order in orders" 
          :key="order._id"
          @click="viewOrderDetail(order)"
		  v-if="order.status != 'cancelled'"
        >
          <view class="trip-info">
            <view class="course-title">{{ order.courseInfo.title }}</view>
            
            <!-- 订单信息 -->
            <view class="order-info">
              <view class="info-item">
                <text class="label">订单编号：</text>
                <text class="value">{{ order._id }}</text>
              </view>
              <view class="info-item">
                <text class="label">创建时间：</text>
                <text class="value">{{ formatDate(order.createTime) }}</text>
              </view>
              <view class="info-item">
                <text class="label">订单金额：</text>
                <text class="value price">¥{{ order.courseInfo.price }}</text>
      </view>
    </view>

            <!-- 订单操作 -->
            <view class="order-actions">
              <view class="action-btn contact" @click.stop="contactService">
                <text class="iconfont icon-service"></text>
                <text>联系客服</text>
              </view>
              <view class="action-btn cancel" @click.stop="cancelOrder(order)" v-if="order.status !== 'cancelled'">
                <text class="iconfont icon-cancel"></text>
                <text>取消行程</text>
              </view>
              <view class="action-btn detail">
                <text class="iconfont icon-detail"></text>
                <text>查看详情</text>
      </view>
    </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <image src="/static/images/empty-trips.png" mode="aspectFit"></image>
        <text>暂无行程</text>
        <button class="browse-btn" @click="browseCourses">浏览课程</button>
    </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orders: [],
      isRefreshing: false
    }
  },
  onLoad() {
    this.loadOrders();
  },
  onShow() {
    // 每次页面显示时刷新数据
    this.refreshOrders();
  },
  methods: {
    // 加载订单
    async loadOrders() {
      try {
        const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || uni.getStorageSync('userInfo');
        if (!userInfo) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }, 1500);
          return;
        }
        
        const res = await uniCloud.callFunction({
          name: 'getOrders',
          data: {
            userId: userInfo._id
          }
        });
        
        if (res.result.code === 0) {
          this.orders = res.result.data;
        } else {
          uni.showToast({
            title: res.result.msg || '加载失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载订单失败', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.isRefreshing = false;
      }
    },
    
    // 刷新订单
    refreshOrders() {
      this.loadOrders();
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      await this.refreshOrders();
    },
    
    // 查看订单详情
    viewOrderDetail(order) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${order._id}`
      });
    },
    
    // 浏览课程
    browseCourses() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    
    // 联系客服
    contactService() {
      uni.showModal({
        title: '联系客服',
        content: '客服电话：400-123-4567',
        confirmText: '拨打',
        success: (res) => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: '4001234567'
            });
          }
        }
      });
    },
    
    // 取消行程
    async cancelOrder(order) {
      try {
        const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || uni.getStorageSync('userInfo');
        if (!userInfo) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          return;
        }
        
        // 显示确认对话框
        const res = await new Promise((resolve, reject) => {
          uni.showModal({
            title: '确认取消',
            content: '确定要取消该行程吗？',
            confirmText: '确定',
            cancelText: '再想想',
            success: resolve,
            fail: reject
          });
        });
        
        if (!res.confirm) return;
        
        // 调用取消行程云函数
        const result = await uniCloud.callFunction({
          name: 'cancelOrder',
          data: {
            orderId: order._id,
            userId: userInfo._id
          }
        });
        
        if (result.result.code === 0) {
          uni.showToast({
            title: '取消成功',
            icon: 'success'
          });
          // 刷新订单列表
          this.refreshOrders();
        } else {
          uni.showToast({
            title: result.result.message || '取消失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('取消行程失败', error);
        uni.showToast({
          title: '取消失败',
          icon: 'none'
        });
      }
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      
      return `${year}-${month}-${day} ${hour}:${minute}`;
    }
  }
}
</script>

<style>
.trip-container {
  min-height: 100vh;
  background-color: #f8f9fc;
      display: flex;
  flex-direction: column;
  }

  .trip-list {
  flex: 1;
  padding: 0 20rpx;
    }

    .trip-item {
      background-color: #fff;
      border-radius: 12rpx;
  margin-bottom: 20rpx;
  display: flex;
      overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      }

      .trip-info {
  flex: 1;
  padding: 30rpx;
        position: relative;
}

.course-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
  margin-bottom: 20rpx;
}

.order-info {
  background-color: #f8f9fc;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
          margin-bottom: 10rpx;
  font-size: 26rpx;
}

.info-item:last-child {
  margin-bottom: 0;
        }

.info-item .label {
          color: #666;
  width: 160rpx;
        }

.info-item .value {
  color: #333;
  flex: 1;
}

.info-item .price {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 28rpx;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx solid #f0f0f0;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.action-btn .iconfont {
  margin-right: 6rpx;
  font-size: 28rpx;
}

.action-btn.contact {
  background-color: #fff7e6;
  color: #fa8c16;
}

.action-btn.cancel {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.action-btn.detail {
  background-color: #e6f7ff;
  color: #1890ff;
          }

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-state image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-state text {
  font-size: 28rpx;
            color: #999;
  margin-bottom: 30rpx;
}

.browse-btn {
  background: linear-gradient(135deg, #4a6ee0, #3a5bc7);
  color: #fff;
  font-size: 28rpx;
  padding: 0 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
}

/* 图标字体 */
@font-face {
  font-family: "iconfont";
  src: url('//at.alicdn.com/t/font_3456789_abcdef.woff2') format('woff2');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 32rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-service:before {
  content: "\e634";
}

.icon-detail:before {
  content: "\e635";
}

.icon-cancel:before {
  content: "\e636";
}
</style>